import { SidebarSchema } from '../schema/schema';
import FdContainerBaseComponent from '../../common/containerBase/containerBase';
import { ElementPropertyConfig } from '@farris/ide-property-panel';
import { SidebarProp } from '../property/property-config';
import { OperateUtils } from '../../../../utils/operate.utils';
import { FormPropertyChangeObject } from '../../../../entity/property-change-entity';
import { DomService } from '@farris/designer-services';

export default class FdSidebarComponent extends FdContainerBaseComponent {
    // 默认是收起
    isOpen = false;
    // 标记动画
    canRemoveInitNoAnimateCls = true;
    // 标记当前
    private sideBarParent = null;
    // 标识当前的legend
    get sidebarKey(): string {
        return `Sidebar-${this.key}`;
    }
    get overlayKey(): string {
        return `Overlay-${this.key}`;
    }
    get closeBtnKey(): string {
        return `CloseBtn-${this.key}`;
    }
    component;
    constructor(component: any, options: any) {
        super(component, options);
    }

    getDefaultSchema(): any {

        return SidebarSchema;
    }

    getTemplateName(): string {
        return 'Sidebar';
    }

    // 渲染模板
    render(children): any {
        return super.render(children || this.renderTemplate('Sidebar', {
            sidebarKey: this.sidebarKey,
            overlayKey: this.overlayKey,
            closeBtnKey: this.closeBtnKey,
            isOpen: this.isOpen,
            canRemoveInitNoAnimateCls: this.canRemoveInitNoAnimateCls,
            children: this.renderComponents(),
            nestedKey: this.nestedKey,
            getToolbarStr: this.getToolbarStr
        }));
    }
    // 绑定事件
    attach(element: any): any {
        // key 如果有多个用 multi，单个用single
        this.loadRefs(element, {
            [this.sidebarKey]: 'single',
            [this.overlayKey]: 'single',
            [this.closeBtnKey]: 'single'
        });
        // 必写
        const superAttach: any = super.attach(element);

        // 注册按钮
        const entryEl = this.refs[this.sidebarKey].querySelector('.f-sidebar-entry-ctr');
        if (entryEl) {
            this.addEventListener(entryEl, 'click', (event) => {
                event.stopPropagation();
                this.openSideBar();
            });
        }
        // 注册关闭按钮
        const closeEl = this.refs[this.closeBtnKey];
        if (closeEl) {
            this.addEventListener(closeEl, 'click', (event) => {
                event.stopPropagation();
                this.closeSideBar();
            });
        }

        // 注册遮罩层
        const overlayEl = this.refs[this.overlayKey];
        this.addEventListener(overlayEl, 'click', (event) => {
            event.stopPropagation();
            this.closeSideBar();
        });

        this.setToolbarBasicInfoMap();

        // 必写
        return superAttach;
    }
    /**
     * 组装属性面板配置数据
     */
    getPropertyConfig(): ElementPropertyConfig[] {
        const serviceHost = this.options.designerHost;
        const prop: SidebarProp = new SidebarProp(serviceHost, this.viewModelId, this.componentId);
        const propertyConfig: ElementPropertyConfig[] = prop.getPropConfig(this.component);
        return propertyConfig;
    }
    /**
     * 属性变更后事件：默认监听样式类属性变更，并触发模板重绘
     * @param changeObject 变更集
     */
    onPropertyChanged(changeObject: FormPropertyChangeObject): void {
        super.onPropertyChanged(changeObject,
            ['position', 'width', 'contentTemplateClass', 'customEntryTemplate',
                'customEntryTemplateClass']);

        if (['header', 'footer'].includes(changeObject.categoryId)) {
            this.triggerRedraw();
        }
    }
    /**
     * 获取工具栏按钮字符串
     */
    getToolbarStr() {
        return OperateUtils.getResponseToolbarStr(this.component.toolbar);
    }
    /**
     * 关闭侧边栏
     */
    private closeSideBar() {
        if (!this.sideBarParent) {
            this.sideBarParent = this.element;
        }
        this.removeNoneAnimateCls();
        this.isOpen = false;
        OperateUtils.removeClass(this.sideBarParent, 'f-sidebar-parent-expand');
        OperateUtils.addClass(this.sideBarParent, 'f-sidebar-parent-collapse');
        this.redraw();
    }
    /**
     * 展开侧边栏
     */
    private openSideBar() {
        if (!this.sideBarParent) {
            this.sideBarParent = this.element;
        }
        this.removeNoneAnimateCls();
        this.isOpen = true;
        OperateUtils.removeClass(this.sideBarParent, 'f-sidebar-parent-collapse');
        OperateUtils.addClass(this.sideBarParent, 'f-sidebar-parent-expand');
        this.redraw();
    }
    /*侧边栏初始因为动画收起时，会被看到, 移除 */
    private removeNoneAnimateCls() {
        if (!this.canRemoveInitNoAnimateCls) {
            return;
        }
        this.canRemoveInitNoAnimateCls = false;
    }

    checkCanMoveComponent(): boolean {

        // 父级节点
        const parent = this.parent && this.parent.component;
        const parentClass = parent && parent.appearance && parent.appearance.class || '';
        const parentClassList = parentClass ? parentClass.split(' ') : [];

        // 1、预置的Sidebar
        if (parentClassList.includes('f-page')) {
            return false;
        }
        return true;
    }
    checkCanDeleteComponent(): boolean {

        // 父级节点
        const parent = this.parent && this.parent.component;
        const parentClass = parent && parent.appearance && parent.appearance.class || '';
        const parentClassList = parentClass ? parentClass.split(' ') : [];

        // 1、预置的Sidebar
        if (parentClassList.includes('f-page')) {
            return false;
        }
        return true;
    }

    /**
     * 设置侧边栏按钮的展示名称和路径，用于交互面板已绑定事件窗口
     */
    private setToolbarBasicInfoMap() {
        if (!this.component.toolbar || !this.component.toolbar.items || !this.component.toolbar.items.length) {
            return;
        }
        const domService = this.options.designerHost.getService('DomService') as DomService;
        const sidebarPath = domService.controlBasicInfoMap.get(this.component.id);

        this.component.toolbar.items.forEach(toolbar => {
            domService.controlBasicInfoMap.set(toolbar.id, {
                showName: toolbar.text,
                parentPathName: `${sidebarPath.parentPathName} > ${toolbar.text}`
            });
        });

    }
}
